package com.madinatek.designproject.client;

import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import javax.media.protocol.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;
import javax.media.bean.playerbean.*;

public class Main extends JFrame implements ActionListener, ControllerListener {
	public MediaPlayer player = null;

	public CaptureDeviceInfo di = null;

	public JButton capture = null;

	public JButton start = null;

	public JButton stop = null;

	public JButton upload = null;

	public Buffer buf = null;

	public Image img = null;

	public VideoFormat vf = null;

	public BufferToImage btoi = null;

	public ImagePanel imgpanel = null;
	
	JPanel southPanel = new JPanel();

	public void start() {
		//super("FPGA-based Camera Pre-processor");
		setLayout(new BorderLayout());
		setSize(new Dimension(320, 600));

		imgpanel = new ImagePanel();
		capture = new JButton("Capture");
		capture.addActionListener(this);

		upload = new JButton("Upload");
		upload.addActionListener(this);

		start = new JButton("Start");
		start.addActionListener(this);

		stop = new JButton("Stop");
		stop.addActionListener(this);
		
		try {
			String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
			di = CaptureDeviceManager.getDevice(str2);
			
			VideoFormat videoformat = (VideoFormat) di.getFormats()[0];
			
			Format myformat = new VideoFormat(videoformat.getEncoding(), videoformat.getSize(), videoformat.getMaxDataLength(), videoformat.getDataType(), 30.0f);
			
			DataSource ds = Manager.createDataSource(di.getLocator());
			
			FormatControl [] frmtCtrl = ((CaptureDevice) ds).getFormatControls();
			frmtCtrl[0].setFormat(myformat);
									
			player = new MediaPlayer();
			player.setDataSource(ds);
			player.realize();
			player.addControllerListener(this);

			start.setEnabled(false);

			southPanel.setLayout(new BorderLayout());			
		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, "Could not locate a firewire Camera.\nPlease connect a firewire camera (DCAM) and install appropriate drivers.");
			//e.printStackTrace();
			return;
		}
		
		JPanel buttonsPanel = new JPanel();

		buttonsPanel.add(start, BorderLayout.WEST);
		buttonsPanel.add(capture, BorderLayout.CENTER);
		buttonsPanel.add(stop, BorderLayout.EAST);

		southPanel.add(buttonsPanel, BorderLayout.CENTER);
		southPanel.add(imgpanel, BorderLayout.SOUTH);

		add(southPanel, BorderLayout.CENTER);
		add(upload, BorderLayout.SOUTH);
		
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				try {
					playerclose();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				//System.exit(0);
				hide();
			}
		});
		
		show();
	}

	
	public synchronized void controllerUpdate (ControllerEvent event) {
		if(event instanceof RealizeCompleteEvent) {
			Component comp = player.getVisualComponent();
			southPanel.add(comp, BorderLayout.NORTH);
			add(southPanel, BorderLayout.CENTER);
			pack();
			setVisible(true);
			player.start();
		}
	}
	
	

	public static void main(String[] args) {
		Main m = new Main();
	}

	public void playerclose() {
		player.close();
		player.deallocate();		
	}

	public void actionPerformed(ActionEvent e) {
		JComponent c = (JComponent) e.getSource();

		if (c == capture) {
			// Grab a frame
			FrameGrabbingControl fgc = (FrameGrabbingControl) player
					.getControl("javax.media.control.FrameGrabbingControl");
			buf = fgc.grabFrame();

			// Convert it to an image
			btoi = new BufferToImage((VideoFormat) buf.getFormat());
			img = btoi.createImage(buf);

			// show the image
			imgpanel.setImage(img);

			// save image
			saveJPG(img, "c:\\test.jpg");
		} else if (c == start) {
			player.start();
			stop.setEnabled(true);
			start.setEnabled(false);
		} else if (c == stop) {
			if (player.getState() == Player.Started) {
				player.stop();
				start.setEnabled(true);
				stop.setEnabled(false);
			}
		} else if (c == upload) {
			/*
			JDialog uploadingWindow = new JDialog();
			uploadingWindow.setTitle("Uploading algorithm package");
			uploadingWindow.add(new UploadingPanel());
			uploadingWindow.addWindowListener(new WindowAdapter() {
				public void windowClosing(final WindowEvent e) {
					upload.setEnabled(true);
				}
			});
			uploadingWindow.setSize(400, 400);
			uploadingWindow.setVisible(true);

			upload.setEnabled(false);
			*/
		}

	}

	class ImagePanel extends Panel {
		public Image myimg = null;

		public ImagePanel() {
			setLayout(null);
			setSize(320, 240);
		}

		public void setImage(Image img) {
			this.myimg = img;
			repaint();
		}

		public void paint(Graphics g) {
			if (myimg != null) {
				g.drawImage(myimg, 0, 0, this);
			}
		}
	}

	public static void saveJPG(Image img, String s) {
		BufferedImage bi = new BufferedImage(img.getWidth(null), img
				.getHeight(null), BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = bi.createGraphics();
		g2.drawImage(img, null, null);

		FileOutputStream out = null;
		try {
			out = new FileOutputStream(s);
		} catch (java.io.FileNotFoundException io) {
			System.out.println("File Not Found");
		}

		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
		param.setQuality(0.5f, false);
		encoder.setJPEGEncodeParam(param);

		try {
			encoder.encode(bi);
			out.close();
		} catch (java.io.IOException io) {
			System.out.println("IOException");
		}
	}
}
